<template>
  <div>
    <el-card shadow="hover" class="layout-padding-auto">
      <TableSearch
        :search="state.search"
        @search="onSearch"
        @listenClick="listenClick"
      />
      <Table
        ref="tableRef"
        v-bind="state.tableData"
        class="table-demo"
        @delRow="onTableDelRow"
        @pageChange="onTablePageChange"
        @listenClick="listenClick"
      >
        <template #default="{ slotData, slotColumn }">
          <div v-if="slotColumn.key === 'orderType'">
            {{
              slotData.orderType == 1
                ? '维修申请'
                : slotData.orderType == 2
                ? '维保申请'
                : '点检申请'
            }}
          </div>
          <div v-if="slotColumn.key === 'dealResult'">
            {{
              slotData.dealResult == 1
                ? '全部退还'
                : slotData.dealResult == 2
                ? '部分退还'
                : slotData.dealResult == 3
                ? '未退还'
                : ''
            }}
          </div>
          <div v-if="slotColumn.key === 'dealStatus'">
            {{ slotData.dealStatus == 0 ? '待处理' : '已处理' }}
          </div>
          <div v-if="slotColumn.key === 'refundFee'">
            {{ slotData.refundFee == 0 ? '-' : slotData.refundFee }}
          </div>
        </template>
      </Table>
      <ForRefund
        :forRefundVisible="forRefundVisible"
        :refundForm="refundForm"
        @cancelRefund="cancelRefund"
        @submitRefund="submitRefund"
      >
      </ForRefund>
      <RefundDetail
        :detailVisible="detailVisible"
        :detailForm="detailForm"
        @closeDetail="closeDetail"
      ></RefundDetail>
      <RefundHandle
        :handleVisible="handleVisible"
        :handleForm="handleForm"
        :totalAmount="totalAmount"
        @closeHandle="closeHandle"
        @submitHandle="submitHandle"
      >
      </RefundHandle>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, reactive, defineAsyncComponent, onMounted } from 'vue'
import { devicePartRefundGetInfoApi, getPartRefundDealApi } from '/@/api/spare'
import { getButtonListByRoleApi } from '/@/api/publicApi'
import { Session } from '/@/utils/storage'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const userinfo = Session.get('shebei')
onMounted(() => {
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/spare/return') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const TableSearch = defineAsyncComponent(
  () => import('/@/components/table/search.vue')
)
const ForRefund = defineAsyncComponent(
  () => import('./components/ForRefund.vue')
)
const RefundDetail = defineAsyncComponent(
  () => import('./components/RefundDetail.vue')
)
const RefundHandle = defineAsyncComponent(
  () => import('./components/RefundHandle.vue')
)
// 定义变量内容
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'refundNum', colWidth: '160', title: '退还单号', type: 'text' },
      { key: 'applyNum', colWidth: '160', title: '原申请单号', type: 'text' },
      { key: 'orderNum', colWidth: '160', title: '关联工单号', type: 'text' },
      { key: 'orderType', colWidth: '120', title: '工单类型', type: 'slot' },
      { key: 'dealStatus', colWidth: '120', title: '处理状态', type: 'slot' },
      { key: 'dealResult', colWidth: '120', title: '处理结果', type: 'slot' },
      {
        key: 'refundUserName',
        colWidth: '160',
        title: '退还申请人',
        type: 'text'
      },
      { key: 'createTime', colWidth: '180', title: '申请时间', type: 'text' },
      {
        key: 'refundAmount',
        colWidth: '200',
        title: '申请退还数量',
        type: 'text'
      },
      {
        key: 'refundFee',
        colWidth: '200',
        title: '退还备件价值(元)',
        type: 'slot'
      },
      {
        key: 'dealUserName',
        colWidth: '160',
        title: '退还处理人',
        type: 'text'
      },
      { key: 'dealTime', colWidth: '180', title: '处理时间', type: 'text' },
      { key: 'remark', colWidth: '120', title: '备注信息', type: 'text' }
    ],
    columnBtn: [
      {
        name: 'refundDetails',
        text: '详情',
        hide(row: any): boolean {
          return true
        },
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'backDetailBtn'
      },
      {
        name: 'refundHandle',
        text: '退还处理',
        hide(row: any): boolean {
          return row.dealStatus == 0 && row.dealUserName == userinfo.realName
        },
        type: 'primary',
        btns: buttonCodes.value,
        btnCode: 'backHandleBtn'
      }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/devicePartRefund/pageList',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: true, // 是否显示表格操作栏
      isExtend: true // 是否可以扩展
    },
    // 搜索参数
    param: {
      // 必传参数，分页的不要传
    },
    extendTable: {
      // 二级表格
      header: [
        { key: 'partNum', colWidth: '', title: '备件编号', type: 'text' },
        { key: 'partName', colWidth: '', title: '备件名称', type: 'text' },
        { key: 'partTypeName', colWidth: '', title: '备件类型', type: 'text' },
        { key: 'amount', colWidth: '', title: '申请数量', type: 'text' }
      ], // 第二级的头部
      dataProp: 'partDetailResponses', // 第二级的数据字段
      isOperate: false // 是否显示表格操作栏
    }
  },
  // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
  search: {
    param: [
      {
        label: '',
        prop: 'keyword',
        placeholder: '输入退还单号/工单号/人名搜索',
        type: 'input'
      },
      {
        label: '处理状态',
        prop: 'dealStatus',
        placeholder: '请选择处理状态',
        options: [
          { id: 0, configValue: '待处理' },
          { id: 1, configValue: '已处理' }
        ],
        type: 'select'
      },
      {
        label: '处理结果',
        prop: 'dealResult',
        placeholder: '请选择处理结果',
        options: [
          { id: 1, configValue: '全部退还' },
          { id: 2, configValue: '部分退还' },
          { id: 3, configValue: '未退还' }
        ],
        type: 'select'
      }
    ],
    btn: [
      {
        text: '申请退还',
        fun: 'forRefund',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'backApplyBtn'
      },
      {
        text: '添加退还',
        fun: 'addRefund',
        disable: false,
        loading: false,
        type: 'primary',
        hide(): boolean {
          return false
        },
        btns: buttonCodes.value,
        btnCode: 'backAddBtn'
      }
    ],
    reset: true
  }
})

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}
// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data })
  // console.log(state.tableData.param);
  state.tableData.flash = !state.tableData.flash
}
// 删除当前项回调
const onTableDelRow = (row: EmptyObjectType) => {
  ElMessage.success(`删除${row.name}成功！`)
  getTableData()
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}

const forRefundVisible = ref(false)
const detailVisible = ref(false)
const handleVisible = ref(false)
const refundForm = ref({
  type: '',
  title: ''
})
const handleForm = ref({
  id: '',
  applyNum: '',
  refundAmount: '',
  partDetailResponses: []
})
const detailForm = ref({})

const forRefund = () => {
  refundForm.value.type = 'for'
  refundForm.value.title = '申请退还'
  forRefundVisible.value = !forRefundVisible.value
}

const addRefund = () => {
  refundForm.value.type = 'add'
  refundForm.value.title = '添加退还'
  forRefundVisible.value = !forRefundVisible.value
}

const cancelRefund = () => {
  forRefundVisible.value = !forRefundVisible.value
}
const submitRefund = () => {
  getTableData()
  forRefundVisible.value = !forRefundVisible.value
}

const refundDetails = (row: any) => {
  devicePartRefundGetInfoApi(row.id).then((res) => {
    if (res.code == 0) {
      detailForm.value = res.data
      detailVisible.value = !detailVisible.value
    }
  })
}
const closeDetail = () => {
  detailVisible.value = !detailVisible.value
}

const totalAmount = ref(0)
const refundHandle = (row: any) => {
  getPartRefundDealApi(row.id).then((res) => {
    if (res.code == 0) {
      console.log('res.data.partDetailResponses', res.data.partDetailResponses)
      let arr = <any>[]
      let partDetailResponses = res.data.partDetailResponses
      partDetailResponses.forEach((item: any) => {
        var b = arr.length
        totalAmount.value += item.amount
        item.partRetrievalDetails.forEach((i: any) => {
          let obj = {
            partNum: item.partNum,
            partName: item.partName,
            partTypeName: item.partTypeName,
            amount: item.amount,
            partId: item.partId,
            rowNum: b,
            price: '',
            batchNum: '',
            batchAmount: '',
            thNum: 0,
            num: item.partRetrievalDetails.length
          }
          obj.price = i.price
          obj.batchNum = i.batchNum
          obj.batchAmount = i.amount
          arr.push(obj)
        })
      })
      handleForm.value.partDetailResponses = arr
      handleForm.value.id = row.id
      handleForm.value.refundAmount = row.refundAmount
      handleForm.value.applyNum = row.applyNum
      handleVisible.value = !handleVisible.value
    }
  })
}

const closeHandle = () => {
  handleVisible.value = false
}
const submitHandle = () => {
  handleVisible.value = false
  getTableData()
}

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  forRefund: forRefund,
  addRefund: addRefund,
  refundDetails: refundDetails,
  refundHandle: refundHandle
}
// 监听子级表格  传过来的方法
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}
</script>
<style scoped lang="scss"></style>
